﻿using System;
using System.Numerics;
using System.Windows;
namespace FantomUI.Util
{
	static class VectorHelper
	{

		/// <summary>
		/// 获得两点的中点。
		/// </summary>
		/// <param name="pt1"></param>
		/// <param name="pt2"></param>
		/// <returns></returns>
		public static Point Mid(this Point pt1, Point pt2)
		{
			return new Point((pt1.X + pt2.X) / 2, (pt1.Y + pt2.Y) / 2);
		}


		/// <summary>
		/// 将向量转换为点。
		/// </summary>
		/// <param name="vec"></param>
		/// <returns></returns>
		public static Point ToPoint(this Vector2 vec)
		{
			return new Point(vec.X, vec.Y);
		}

		/// <summary>
		/// 调整点的相对偏移位置。
		/// </summary>
		/// <param name="point"></param>
		/// <param name="vec"></param>
		/// <returns></returns>
		public static Point Add(this Point point, Vector2 vec)
		{
			return new Point(point.X + vec.X, point.Y + vec.Y);
		}

		/// <summary>
		/// 两点相减获得距离矢量。
		/// </summary>
		/// <param name="pt1"></param>
		/// <param name="pt2"></param>
		/// <returns></returns>
		public static Vector2 Sub(this Point pt1, Point pt2)
		{
			return new Vector2((float)(pt1.X - pt2.X), (float)(pt1.Y - pt2.Y));
		}

		/// <summary>
		/// 获得向量的长度。
		/// </summary>
		/// <param name="vec"></param>
		/// <returns></returns>
		public static float GetDistance(this Vector2 vec)
		{
			return MathF.Sqrt(vec.X * vec.X + vec.Y * vec.Y);
		}

		/// <summary>
		/// 获得长度。
		/// </summary>
		/// <param name="vec"></param>
		/// <returns></returns>
		public static Vector2 Normalize(this Vector2 vec)
		{
			var dis = vec.GetDistance();
			return new Vector2() { X = vec.X / dis, Y = vec.Y / dis };
		}

		/// <summary>
		/// 为向量重设角度。
		/// </summary>
		public static Vector2 SetRotation(this Vector2 vec, float rotation)
		{
			var dis = vec.GetDistance();
			return new Vector2(MathF.Cos(rotation) * dis, MathF.Sin(rotation) * dis);
		}

		/// <summary>
		/// 获得向量的方向。
		/// </summary>
		/// <param name="vec"></param>
		/// <returns></returns>
		public static float GetRotation(this Vector2 vec)
		{
			var temp = MathF.Atan(vec.Y / vec.X);
			// 如果为横坐标的负半轴。
			if (vec.X < 0)
			{
				temp = temp + MathF.PI;
			}

			return temp;
		}


		/// <summary>
		/// 极小值过滤，可以将一些极为小的值变为0d。
		/// </summary>
		/// <param name="num"></param>
		/// <returns></returns>
		private static float FilterMinValue(float num)
		{
			if (num < 1E-6 && num > -1E-6)
				return 0;
			else
				return num;
		}

		/// <summary>
		/// 旋转增量
		/// </summary>
		/// <param name="vec"></param>
		/// <param name="rotation"></param>
		/// <returns></returns>
		public static Vector2 IncreaseRotation(this Vector2 vec, float rotation)
		{
			var dis = vec.GetDistance();
			var temp = vec.GetRotation();
			var rot = rotation;
			float cos = 0f;
			float sin = 0f;

			rot += temp;

			cos = FilterMinValue(MathF.Cos(rot));
			sin = FilterMinValue(MathF.Sin(rot));

			var x = dis * cos;
			var y = dis * sin;
			return new Vector2(x, y);
		}


	}
}
